package org.moonholder.springboot.damocles.config;

import lombok.extern.slf4j.Slf4j;
import org.moonholder.springboot.damocles.entity.User;
import org.springframework.context.ApplicationListener;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.session.HttpSessionCreatedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 监听session创建对象
 */
@Component
@Slf4j
class HttpSessionCreatedEventListener implements ApplicationListener<HttpSessionCreatedEvent> {

    @Resource
    private SessionManage sessionManage;

    @Override
    public void onApplicationEvent(HttpSessionCreatedEvent event) {
        String sessionId = event.getSession().getId();
        log.info("新建session:{}", sessionId);
        try {
            // 保存 session
            HttpSession session = event.getSession();
            SecurityContext securityContext = (SecurityContext) session.getAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
            Object principal = securityContext.getAuthentication().getPrincipal();
            if (principal instanceof User) {
                User user = (User) principal;
                sessionManage.putUserSession(user.getId().toString(), session);
            }
        } catch (Exception e) {
            log.info(String.format("添加session:[%s]出现异常.", event.getSession().getId()), e);
        }
    }
}